package com.sz.lk.wingsystem.ui;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import androidx.core.app.ActivityCompat;

import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.sz.lk.wingsystem.MainApp;
import com.sz.lk.wingsystem.R;
import com.sz.lk.wingsystem.bean.LoginResult;
import com.sz.lk.wingsystem.mbluetooth.Params;
import com.sz.lk.wingsystem.mutils.SaveUtils;
import com.sz.lk.wingsystem.mutils.ToastUtils;
import com.sz.lk.wingsystem.mvp.BaseActivity;
import com.sz.lk.wingsystem.mvp.ModelPath;
import com.sz.lk.wingsystem.mvp.contract.LoginContract;
import com.sz.lk.wingsystem.mvp.presenter.LoginPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 *    @author : liuke
 *    e-mail : 1012459343@qq.com
 *    date   : 2020/12/9
 *    desc   :
 *    version: 1.0
 */
public class MainActivity extends BaseActivity<LoginPresenter> implements LoginContract.view {

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.lg_bt)
    Button lgBt;
    BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initEventAndData() {
        checkPermissionRequestEachCombined(this);
        String loginflag = (String) SaveUtils.getInstance().get(this, "login", "fail");
        if ("success".equals(loginflag)) {
            startActivity(new Intent(this, MenuPage.class));
            finish();
        }
        String username = (String) SaveUtils.getInstance().get(this, "username", "123456");
        name.setText(username);
    }

    public void checkPermissionRequestEachCombined(Activity activity) {
        RxPermissions permissions = new RxPermissions(activity);
        permissions.setLogging(true);
        Disposable permissionsDisposable = permissions.requestEachCombined(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(permission -> {
                    if (permission.granted) {//全部同意后调用
                        if (Build.VERSION.SDK_INT >= 6.0) {
                            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    Params.MY_PERMISSION_REQUEST_CONSTANT);
                        }
                        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        try {
                            bluetoothAdapter.disable();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {//只要有一个选择：禁止，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                        ToastUtils.show("用户拒绝开启" + permission.name + "读写权限,app无法使用");
                    } else {//只要有一个选择：禁止，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                        // 用户拒绝了该权限，并且选中『不再询问』
                        ToastUtils.show("用户拒绝了该权限，并且选中『不再询问』");
                    }
                });
        mCompositeDisposable.add(permissionsDisposable);
    }


    @Override
    protected LoginPresenter initPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void onLoginSuccess(LoginResult bean) {
        if (bean.isIsSucceed()) {
            SaveUtils.getInstance().save(this, "login", "success");
            startActivity(new Intent(this, MenuPage.class));
            finish();
        } else {
            ToastUtils.show("登录失败，请稍后再试");
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void onError(Throwable throwable) {
        ToastUtils.show("登录异常！");
    }

    @Override
    public void showWaitingDialog(String tip) {

    }

    @Override
    public void hideWaitingDialog() {

    }

    @OnClick(R.id.lg_bt)
    public void onViewClicked() {
        String account = name.getText().toString().trim();
        String pass = password.getText().toString().trim();
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(pass)) {
            SaveUtils.getInstance().save(this, "username", account);
            loginRequest(account, pass);
           /* startActivity(new Intent(this, MenuPage.class));
            finish();*/
            //4.3无法使用okhttp 字符编码起码要4.4以上
            //mPresenter.Get_Login(account, pass);
        } else {
            ToastUtils.show("账号密码不能为空！");
        }
    }

    public void loginRequest(String account, String pass) {
        Map<String, String> merchant = new HashMap<>();
        merchant.put("userName", account);
        merchant.put("password", pass);
        JSONObject jsonObject = new JSONObject(merchant);
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, ModelPath.baseUrl_NO_Splite + "User/Login", jsonObject,
                response -> {
                    String a = response.toString();
                    Log.e("Main", a);
                    onLoginSuccess(new Gson().fromJson(a, LoginResult.class));
                }, error -> {
            ToastUtils.show(error.getMessage());
        }) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };
        MainApp.mQueue.add(jsonRequest);
    }
}